package com.example.universitylibraryback.service.impl;

import com.example.universitylibraryback.mapper.BookMapper;
import com.example.universitylibraryback.mapper.BorrowRecordMapper;
import com.example.universitylibraryback.mapper.ReaderMapper;
import com.example.universitylibraryback.entity.Book;
import com.example.universitylibraryback.entity.BorrowRecord;
import com.example.universitylibraryback.entity.Reader;
import com.example.universitylibraryback.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class BorrowServiceImpl implements BorrowService {
    
    @Autowired
    private BookMapper bookMapper;
    
    @Autowired
    private ReaderMapper readerMapper;
    
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;
    
    @Override
    @Transactional
    public boolean borrowBook(String bookId, String readerId, String operatorRole) {
        // 1. 获取读者和图书信息
        Reader reader = readerMapper.findById(readerId);
        Book book = bookMapper.findById(bookId);
        
        // 2. 检查借阅条件
        if (reader == null || book == null) {
            return false;
        }
        
        // 检查读者是否有借阅权限
        if (!canReaderBorrow(reader)) {
            return false;
        }
        
        // 检查图书是否可借
        if (!"可借".equals(book.getBookStatus()) || book.getStock() <= 0) {
            return false;
        }
        
        // 3. 创建借阅记录
        BorrowRecord record = new BorrowRecord();
        record.setRecordId(UUID.randomUUID().toString());
        record.setReaderId(readerId);
        record.setBookId(bookId);
        record.setOperatorRole(operatorRole);
        record.setBorrowDate(new Date());
        
        // 设置到期日期（例如：30天后）
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, 30);
        record.setDueDate(calendar.getTime());
        
        record.setRenewCount(0);
        record.setStatus("在借");
        record.setCreateTime(new Date());
        
        // 4. 保存借阅记录
        borrowRecordMapper.insert(record);
        
        // 5. 更新图书状态
        bookMapper.updateBookStatus(bookId, "已借");
        book.setStock(book.getStock() - 1);
        bookMapper.update(book);
        
        return true;
    }
    
    @Override
    @Transactional
    public boolean returnBook(String bookId, String readerId) {
        // 1. 查找未归还的借阅记录
        List<BorrowRecord> records = borrowRecordMapper.findByReaderId(readerId);
        BorrowRecord recordToUpdate = null;
        
        for (BorrowRecord record : records) {
            if (record.getBookId().equals(bookId) && "在借".equals(record.getStatus())) {
                recordToUpdate = record;
                break;
            }
        }
        
        if (recordToUpdate == null) {
            return false;
        }
        
        // 2. 更新借阅记录
        borrowRecordMapper.updateReturnInfo(recordToUpdate.getRecordId(), "已还", new Date());
        
        // 3. 更新图书状态
        bookMapper.updateBookStatus(bookId, "可借");
        
        // 4. 增加图书库存
        Book book = bookMapper.findById(bookId);
        if (book != null) {
            book.setStock(book.getStock() + 1);
            bookMapper.update(book);
        }
        
        return true;
    }
    
    @Override
    @Transactional
    public boolean renewBook(String recordId) {
        // 1. 查找借阅记录
        BorrowRecord record = borrowRecordMapper.findById(recordId);
        if (record == null || !"在借".equals(record.getStatus())) {
            return false;
        }
        
        // 2. 检查是否可以续借（最多续借1次）
        if (record.getRenewCount() >= 1) {
            return false;
        }
        
        // 3. 检查是否已超期
        if (new Date().after(record.getDueDate())) {
            return false;
        }
        
        // 4. 更新续借信息
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(record.getDueDate());
        calendar.add(Calendar.DAY_OF_MONTH, 30); // 续借30天
        
        borrowRecordMapper.updateRenewCount(recordId, record.getRenewCount() + 1, calendar.getTime());
        
        return true;
    }
    
    @Override
    public List<BorrowRecord> getBorrowRecordsByReaderId(String readerId) {
        return borrowRecordMapper.findByReaderId(readerId);
    }
    
    @Override
    public List<BorrowRecord> getOverdueRecords() {
        return borrowRecordMapper.findOverdueRecords();
    }
    
    @Override
    public BorrowRecord getBorrowRecordById(String recordId) {
        return borrowRecordMapper.findById(recordId);
    }
    
    // 检查读者是否有借阅权限的辅助方法
    private boolean canReaderBorrow(Reader reader) {
        // 检查读者状态
        if (!"正常".equals(reader.getStatus())) {
            return false;
        }
        
        // 这里可以添加更多的借阅权限检查逻辑
        // 例如：检查读者是否有逾期未还的图书
        List<BorrowRecord> overdueRecords = borrowRecordMapper.findOverdueRecords();
        for (BorrowRecord record : overdueRecords) {
            if (record.getReaderId().equals(reader.getReaderId())) {
                return false;
            }
        }
        
        return true;
    }
}